package buildrequest

import (
	"fmt"
	"log"
	"net"
	"time"

	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
)

/*
构建包
*/
var (
	snapshot_len int32 = 1024
	promiscuous  bool  = false
	err          error
	timeout      time.Duration = 30 * time.Second
	handle       *pcap.Handle
	buffer       gopacket.SerializeBuffer
	options      gopacket.SerializeOptions
)

/*
模拟构建发送包
*/
func Build(device string) {
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	raw := []byte{10, 20, 30}
	//如果值只发数据，会报错，，所以改为记录错误。
	err = handle.WritePacketData(raw)
	if err != nil {
		log.Print(err)
	}
	buffer = gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		&layers.Ethernet{},
		&layers.IPv4{},
		&layers.TCP{},
		gopacket.Payload(raw),
	)
	upstreamPacket := buffer.Bytes()

	//发送包
	//fmt.Println(upstreamPacket)
	err = handle.WritePacketData(upstreamPacket)
	if err != nil {
		log.Fatal(err)
	}
	ipLayer := &layers.IPv4{SrcIP: net.ParseIP("192.168.2.37"), DstIP: net.ParseIP("192.168.2.26")}
	srcMac, _ := net.ParseMAC("68:07:15:42:29:1c")
	dstMac, _ := net.ParseMAC("1C:77:F6:88:68:F0")
	ethernetLayer := &layers.Ethernet{SrcMAC: srcMac, DstMAC: dstMac}
	tcpLayer := &layers.TCP{SrcPort: 81, DstPort: 11111}

	buffer = gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		ethernetLayer, ipLayer, tcpLayer, gopacket.Payload(raw),
	)
	upstreamPacket = buffer.Bytes()
	fmt.Println(upstreamPacket)
	//发送包
	err = handle.WritePacketData(upstreamPacket)
	if err != nil {
		log.Fatal(err)
	}
}
